package cn.stylefeng.guns.modular.kh.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicOperate;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.kehao.entity.KhLyOutOrder;
import cn.stylefeng.guns.modular.kh.entity.KhWare;
import cn.stylefeng.guns.modular.kh.mapper.KhWareMapper;
import cn.stylefeng.guns.modular.kh.model.params.KhWareParam;
import cn.stylefeng.guns.modular.kh.model.result.KhWareResult;
import  cn.stylefeng.guns.modular.kh.service.KhWareService;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 可好-波次信息 服务实现类
 * </p>
 *
 * @author zzh
 * @since 2025-10-21
 */
@Service
public class KhWareServiceImpl extends ServiceImpl<KhWareMapper, KhWare> implements KhWareService {

    @Autowired
    private DictService dictService;

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private BasicOperateService basicOperateService;

    @Override
    public void add(KhWareParam param){
        KhWare entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(KhWareParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(KhWareParam param){
        KhWare oldEntity = getOldEntity(param);
        KhWare newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public KhWareResult findBySpec(KhWareParam param){
        return null;
    }

    @Override
    public List<KhWareResult> findListBySpec(KhWareParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(KhWareParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData getExceldata(MultipartFile file, User user) {
        ResponseData data = new ResponseData();
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        try {
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            Sheet sheet = wb.getSheetAt(0);

            List<DictResult> waveNumList = this.dictService.findByDicttypeCode2("KH_BC");
            Map<String,String> waveNumMap = new HashMap<>();
            for(DictResult obj : waveNumList){
                waveNumMap.put(obj.getName(),obj.getCode());
            }

            BasicPutgoodsParam q = new BasicPutgoodsParam();
            q.setUnitType("门店");
            List<BasicPutgoodsResult> putgoodsList = basicPutgoodsService.findListBySpec(q, user.getOperateId());
            Map<String,BasicPutgoodsResult> putgoodsMap = new HashMap<>();
            for(BasicPutgoodsResult obj : putgoodsList){
                putgoodsMap.put(obj.getUnitNumber(),obj);
            }
            BasicOperate basicOperate = null;
            if(ToolUtil.isNotEmpty(user.getOperateId())){
                basicOperate = this.basicOperateService.getById(user.getOperateId());
            }
            StringBuffer errStr = new StringBuffer();
            KhWare khWareAdd;
            List<KhWare> khWareAddList = new ArrayList<>();
            for (int r = 1; r <= sheet.getLastRowNum() + 1; r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }

                khWareAdd = new KhWare();
                // 所属波次
                String  waveNumName = getCellValue(row.getCell(0));
                if(ToolUtil.isEmpty(waveNumName) || ToolUtil.isEmpty(waveNumMap.get(waveNumName))){
                    errStr.append(r+1).append("行").append("[").append(waveNumName).append("]波次不存在").append("</br>");
                    throw new Exception(errStr.toString());
                }
                khWareAdd.setWaveNum(waveNumMap.get(waveNumName));

                // 客户编码
                String  getUnitNumber = getCellValue(row.getCell(1));
                if(ToolUtil.isEmpty(getUnitNumber) || ToolUtil.isEmpty(putgoodsMap.get(getUnitNumber))){
                    errStr.append(r+1).append("行").append("[").append(getUnitNumber).append("]门店不存在").append("</br>");
                    throw new Exception(errStr.toString());
                }
                Integer count = this.lambdaQuery()
                        .eq(KhWare::getGetUnitId,putgoodsMap.get(getUnitNumber).getId())
                        .count();

                if(count > 0){
                    errStr.append(r+1).append("行").append("[").append(getUnitNumber).append("]门店已存在").append("</br>");
                }

                khWareAdd.setGetUnitNumber(getUnitNumber);
                khWareAdd.setGetUnit(putgoodsMap.get(getUnitNumber).getPutgoodsName());
                khWareAdd.setGetUnitId(putgoodsMap.get(getUnitNumber).getId().longValue());

                // 门店编码
                String  getUnitSort = getCellValue(row.getCell(3));

                if(ToolUtil.isEmpty(getUnitSort)){
                    errStr.append(r+1).append("行").append("收货客户序号不能为空").append("</br>");
                }
                khWareAdd.setGetUnitSort(getUnitSort);

                // 集货通道
                String  stockPort = getCellValue(row.getCell(4));
                if(ToolUtil.isEmpty(stockPort)){
                    errStr.append(r+1).append("行").append("集货通道不能为空").append("</br>");
                }
                khWareAdd.setStockPort(stockPort);

                // 播种位
                String  toLocation = getCellValue(row.getCell(5));
                if(ToolUtil.isEmpty(toLocation)){
                    errStr.append(r+1).append("行").append("播种位不能为空").append("</br>");
                }
                khWareAdd.setToLocation(toLocation);

                khWareAdd.setCreateUser(user.getUserId());
                khWareAdd.setCreateTime(new Date());
                if(ToolUtil.isNotEmpty(basicOperate)){
                    khWareAdd.setOperateId(basicOperate.getId());
                    khWareAdd.setOperateName(basicOperate.getOperateName());
                }
                khWareAddList.add(khWareAdd);
            }
            if(errStr.length() > 0){
                throw new Exception(errStr.toString());
            }

            if(ToolUtil.isNotEmpty(khWareAddList) && khWareAddList.size() > 0){
                this.saveBatch(khWareAddList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseData.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error(e.getMessage());
        }
        return ResponseData.success();
    }

    private Serializable getKey(KhWareParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private KhWare getOldEntity(KhWareParam param) {
        return this.getById(getKey(param));
    }

    private KhWare getEntity(KhWareParam param) {
        KhWare entity = new KhWare();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

}
